﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LuaInterface;
using UnityEngine.EventSystems;

public class LuaBehaviour : MonoBehaviour
{
    //对应的lua脚本名
    public string scriptName;
    //lua层的behaviour对象，可在lua层获取
    public LuaTable Self { get; private set; }

    protected virtual void Awake()
    {
        if (string.IsNullOrEmpty(scriptName))
        {
            scriptName = gameObject.name;
            if (scriptName.EndsWith("(Clone)"))
            {
                scriptName = scriptName.Substring(0, scriptName.Length - 7);
            }
        }

        //获取lua层中对应的behaviour对象
        Self = LuaManager.Instance.LuaState.DoFile<LuaTable>(scriptName);

        if (Self == null)
        {
            Debug.LogError(gameObject.name + " Self is null");
            return;
        }

        //传递基本属性给lua层
        Self["gameObject"] = gameObject;
        Self["transform"] = transform;

        CallLuaFunc("Awake");
    }

    protected virtual void Start()
    {
        CallLuaFunc("Start");
    }

    protected virtual void OnEnable()
    {
        CallLuaFunc("OnEnable");
    }

    protected virtual void OnDisable()
    {
        CallLuaFunc("OnDisable");
    }

    protected virtual void OnApplicationQuit()
    {
        CallLuaFunc("OnApplicationQuit");
    }

    protected virtual void OnDestroy()
    {
        CallLuaFunc("OnDestroy");

        if (Self != null)
        {
            Self.Dispose();
            Self = null;
        }
    }

    //调用lua中实现的函数
    protected object[] CallLuaFunc(string funcName, params object[] args)
    {
        if (Self == null)
        {
            return null;
        }

        //获取lua函数
        LuaFunction func = (LuaFunction)Self[funcName];

        if (func == null)
        {
            return null;
        }

        //等价于lua语句: Self:func(...)

        int oldTop = func.BeginPCall();
        //调用lua中:形式的函数必须先push self
        func.Push(Self);
        func.PushArgs(args);
        func.PCall();
        object[] result = LuaManager.Instance.LuaState.CheckObjects(oldTop);
        func.EndPCall();
        func.Dispose();
        func = null;

        return result;
    }

}
